<template>
   <div>
      <el-breadcrumb separator="/">
         <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item><a href="javascript:;">广告管理</a></el-breadcrumb-item>
         <el-breadcrumb-item>广告列表</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="hengxian"></div>

      <el-row>
         <el-col :span="13">
            <el-button type="primary" size="mini" @click="dialogTableCreate = true">
               <i class="el-icon-plus"></i><span>新增</span>
            </el-button>
            <el-button type="danger" size="mini" @click="handleDeleteMultiple">
               <i class="el-icon-delete"></i><span>删除</span>
            </el-button>
         </el-col>
         <el-col :span="5">
            <el-select v-model="cate_id" placeholder="请选择" @change="handleSelectChange(cate_id)" size="mini">
               <el-option v-for="item in advert_nodes" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
         </el-col>
         <el-col :span="5">
            <el-input placeholder="请输入内容" v-model="keyword" class="input-with-select" size="mini">
               <el-select v-model="cate" slot="prepend" placeholder="请选择">
                  <el-option label="ID" value="id"></el-option>
                  <el-option label="标题" value="title"></el-option>
               </el-select>
               <el-button slot="append" @click="handleSearch" icon="el-icon-search"></el-button>
            </el-input>
         </el-col>
      </el-row>

      <el-table ref="multipleTable" :data="adverts" tooltip-effect="dark" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading">
         <el-table-column type="selection" width="55"></el-table-column>
         <el-table-column prop="id" label="ID"></el-table-column>
         <el-table-column prop="image" label="缩略图">
            <template slot-scope="scope">
               <img v-if="scope.row.image" :src="scope.row.image" @click="handleShow(scope.$index,scope.row)" alt=""
                    class="image">
            </template>
         </el-table-column>
         <el-table-column prop="title" label="标题"></el-table-column>
         <el-table-column prop="category_id" label="所属类别">
            <template slot-scope="scope">
               <el-tag v-if="scope.row.cate_name" type="success">{{ scope.row.cate_name}}</el-tag>
            </template>
         </el-table-column>
         <el-table-column prop="url" label="URL地址">
            <template slot-scope="scope">
               <el-link :href="scope.row.url" type="primary" target="_blank">{{scope.row.url}}</el-link>
            </template>
         </el-table-column>
         <el-table-column prop="description" label="描述" width="260">
            <template slot-scope="scope">{{scope.row.description|edit_desc}}</template>
         </el-table-column>
         <el-table-column prop="is_show" label="是否显示" width="80">
            <template slot-scope="scope">
               <i :class="scope.row.is_show ? 'el-icon-success' : 'el-icon-error'"
                  @click="change_attr(scope.row,'is_show')"></i>
            </template>
         </el-table-column>
         <el-table-column prop="sort_order" label="排序" :label-width="formLabelWidth">
            <template slot-scope="scope">
               <el-input-number v-model="scope.row.sort_order" :min="1" :max="999" size="mini"
                                @change="handleChange(scope.row.id,scope.row.sort_order)"></el-input-number>
            </template>
         </el-table-column>
         <el-table-column prop="created_at" label="创建日期" width="170"></el-table-column>
         <el-table-column label="操作" width="100">
            <template slot-scope="scope">
               <i class="el-icon-edit-outline" @click="handleEdit(scope.$index,scope.row)"></i>
               <i class="el-icon-delete" @click="handleDelete(scope.$index,scope.row)"></i>
            </template>
         </el-table-column>
      </el-table>

      <!--分页-->
      <div class="page">
         <span class="total">共 {{page.total}} 条数据</span>
         <el-pagination background :total="page.total" :page-size="page.size" @current-change="handleCurrentChange"
                        :current-page.sync="page.currentPage" layout="prev, pager, next">
         </el-pagination>
      </div>

      <!--查看大图-->
      <el-dialog :visible.sync="showImg" :width="width" custom-class="an-img-dialog" :center="true">
         <img :src="advert.image" alt="" @load="onLoad">
      </el-dialog>

      <!--新增广告-->
      <el-dialog title="新增广告" :visible.sync="dialogTableCreate" @close='closeDialog'>
         <el-form :model="advert" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="所属分类" prop="category_id">
               <el-select v-model="advert.category_id" placeholder="请选择">
                  <el-option v-for="item in advert_nodes" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title">
               <el-input v-model="advert.title"></el-input>
            </el-form-item>
            <el-form-item label="缩略图" prop="image">
               <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                  <img v-if="advert.image" :src="advert.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
            </el-form-item>
            <el-form-item label="URL地址" prop="url">
               <el-input placeholder="请输入带http://开头的URL地址" v-model="advert.url"></el-input>
            </el-form-item>
            <el-form-item label="是否显示" prop="is_show">
               <el-switch v-model="advert.is_show"></el-switch>
            </el-form-item>
            <el-form-item label="排序" prop="sort_order">
               <el-input-number v-model="advert.sort_order" @change="handleCreateChange" :min="1"
                                :max="999"></el-input-number>
            </el-form-item>
            <el-form-item label="描述" prop="description">
               <el-input type="textarea" v-model="advert.description"></el-input>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" size="mini" @click="submitForm('ruleForm')">保存</el-button>
               <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
         </el-form>
      </el-dialog>

      <!--编辑广告-->
      <el-dialog title="新增广告" :visible.sync="dialogTableEdit" @close='closeDialog'>
         <el-form :model="advert" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="所属分类" prop="category_id">
               <el-select v-model="advert.category_id" placeholder="请选择">
                  <el-option v-for="item in advert_nodes" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title">
               <el-input v-model="advert.title"></el-input>
            </el-form-item>
            <el-form-item label="缩略图" prop="image">
               <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                  <img v-if="advert.image" :src="advert.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
            </el-form-item>
            <el-form-item label="URL地址" prop="url">
               <el-input placeholder="请输入带http://开头的URL地址" v-model="advert.url"></el-input>
            </el-form-item>
            <el-form-item label="是否显示" prop="is_show">
               <el-switch v-model="advert.is_show"></el-switch>
            </el-form-item>
            <el-form-item label="排序" prop="sort_order">
               <el-input-number v-model="advert.sort_order" @change="handleCreateChange" :min="1"
                                :max="999"></el-input-number>
            </el-form-item>
            <el-form-item label="描述" prop="description">
               <el-input type="textarea" v-model="advert.description"></el-input>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" size="mini" @click="updateForm('ruleForm')">保存</el-button>
               <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
         </el-form>
      </el-dialog>
   </div>
</template>

<script>
   export default {
      name: "Home",
      data() {
         return {
            loading: false,
            showImg: false,
            width: '',
            dialogTableCreate: false,
            adverts: [],
            multipleSelection: [],
            formLabelWidth: 120,
            advert_nodes: [],
            cate_id: '',
            keyword: '',
            cate: '',
            page: {
               total: 0,  //总数
               size: 0,  //每页显示数
               currentPage: 1,
            },
            advert: {
               image: '',
               title: '',
               category_id: '',
               url: '',
               description: '',
               is_show: '',
               sort_order: 99
            },
            rules: {
               category_id: [
                  {required: true, message: '请选择广告分类', trigger: 'change'}
               ],
               title: [
                  {required: true, message: '请输入广告名称', trigger: 'blur'},
                  {min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
               ],
            },
            dialogTableEdit: false,
         }
      },
      created() {
         this.init();
      },
      filters: {
         edit_desc: function (val) {
            return val.substring(0, 15) + '...';
         }
      },
      methods: {
         onLoad(e) {
            const img = e.target;
            let width = 0;
            if (img.fileSize > 0 || (img.width > 1 && img.height > 1)) {
               width = img.width + 45;
            }
            this.width = width + 'px';
         },
         //点击查看大图
         handleShow(index, row) {
            this.advert.image = row.image;
            this.showImg = true;
         },
         //分页--获取当前页
         handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.page.currentPage = val;
            this.init();
         },
         //按分类搜索
         handleSelectChange(val) {
            // console.log(val);
            this.cate_id = val;
            this.init();
         },
         //关键字搜索
         handleSearch() {
            this.init();
         },
         //改变排序
         handleCreateChange(value) {
            this.category.sort_order = value;
         },
         //首页
         init() {
            this.loading = true;
            const category_id = this.$route.params.category_id || this.cate_id;  //前者为查看分类发送过来的id,后者为默认值
            axios.get(`/admin/ad/adverts?page=${this.page.currentPage}&category_id=${category_id}&cate=${this.cate}&keyword=${this.keyword}`)
               .then((res) => {
                  // console.log(res.data);
                  this.adverts = res.data.data;
                  this.page.total = res.data.total;
                  this.page.size = res.data.per_page;
                  this.loading = false;
               });
            //所有分类
            axios.get(`/admin/ad/advert_nodes`)
               .then((res) => {
                  this.advert_nodes = res.data;
               })
         },
         //改变属性
         change_attr(row, attr) {
            axios.patch(`/admin/ad/adverts/change_attr`, {id: row.id, attr: attr})
               .then((res) => {
                  this.$notify({
                     title: '成功',
                     message: '改变状态成功',
                     type: 'success'
                  });
                  this.init();
               });
         },
         //排序
         handleChange(id, sort_order) {
            axios.patch(`/admin/ad/adverts/change_sort`, {id: id, sort_order: sort_order})
               .then((res) => {
                  this.$message({
                     showClose: true,
                     message: '排序成功~',
                     type: 'success',
                  });
                  this.init();
               });
         },
         //图片上传
         handleAvatarSuccess(res, file) {
            this.advert.image = res.msg;
         },
         beforeAvatarUpload(file) {
            // const isJPG = file.type === 'image/jpeg';
            const img = ['image/jpeg', 'image/png', 'image/gif'];
            const isJPG = img.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
               this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
            }
            if (!isLt2M) {
               this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
         },
         //关闭模态框,先清空验证再清除表单
         closeDialog() {
            this.$refs.ruleForm.clearValidate();
            this.$refs.ruleForm.resetFields();
            this.advert = {};  //清空表单值
         },
         //新增
         submitForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  axios.post(`/admin/ad/adverts`, this.advert)
                     .then((res) => {
                        if (res.data.status == 1) {
                           this.$message({
                              showClose: true,
                              message: res.data.msg,
                              type: 'success'
                           });
                           this.dialogTableCreate = false;
                           this.init();
                           this.$refs[formName].resetFields();  //重置表单
                        } else {
                           this.$message.error(res.data.msg);
                        }
                     })
               } else {
                  this.$message({
                     showClose: true,
                     message: '新增广告失败',
                     type: 'error'
                  });
                  return false;
               }
            });
         },
         resetForm(formName) {
            this.$refs[formName].resetFields();
         },
         //编辑模态框
         handleEdit(index, row) {
            axios.get(`/admin/ad/adverts/${row.id}`)
               .then((res) => {
                  this.dialogTableEdit = true;
                  this.advert = res.data;
                  this.advert.is_show = !!res.data.is_show;
               })
         },
         //更新
         updateForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  axios.put(`/admin/ad/adverts/${this.advert.id}`, this.advert)
                     .then((res) => {
                        this.$message({
                           showClose: true,
                           message: '编辑广告成功',
                           type: 'success'
                        });
                        this.dialogTableEdit = false;
                        this.init();
                     })
               } else {
                  console.log('error submit!!');
                  return false;
               }
            });
         },
         //删除
         handleDelete(index, row) {
            this.$confirm('确认删除该条文章?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning'
            }).then(() => {
               axios.delete(`/admin/ad/adverts/${row.id}`)
                  .then((res) => {
                     this.adverts.splice(index, 1);
                     this.$message({
                        type: 'success',
                        message: '删除成功!'
                     });
                  });
            }).catch(() => {
               this.$message({
                  type: 'warning',
                  message: '已取消删除'
               });
            });
         },
         //获取选中的值
         handleSelectionChange(val) {
            this.multipleSelection = val;
         },
         //多选删除
         handleDeleteMultiple() {
            if (this.multipleSelection.length == 0) {
               this.$message({
                  message: '至少选择一条数据',
                  type: 'warning'
               });
            } else {
               this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
               }).then(() => {
                  const checked_id = this.multipleSelection.map((item) => {
                     return item.id;
                  });
                  axios.post(`/admin/ad/adverts/delete_all`, {checked_id: checked_id})
                     .then((res) => {
                        this.$message({
                           type: 'success',
                           message: '删除成功!'
                        });
                        this.init();
                     });
               }).catch(() => {
                  this.$message({
                     type: 'info',
                     message: '已取消删除'
                  });
               });
            }
         },
      }
   }
</script>

<style>
   .el-row {
      margin-bottom: 15px;
   }

   .el-select {
      width: 130px;
   }

   .image {
      width: 80px;
      height: 30px;
      cursor: pointer;
   }

   .input-with-select .el-input-group__prepend {
      background-color: #fff;
   }

   .el-table td {
      padding: 3px 0;
   }

   .el-input__inner {
      padding: 0 2px;
   }

   .page {
      margin-top: 15px;
   }

   .el-pagination {
      float: right;
   }
</style>